import noPicture from '@/assets/png/no-picture.png';
import {
  FullscreenExitOutlined,
  FullscreenOutlined,
  LeftOutlined,
  ReloadOutlined,
  RightOutlined,
  RotateLeftOutlined,
  RotateRightOutlined,
  ZoomInOutlined,
  ZoomOutOutlined,
} from '@ant-design/icons';
import { Button, Space, Tooltip } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { TransformComponent, TransformWrapper } from 'react-zoom-pan-pinch';
import './index.less';

interface ImageViewerProps {
  urls: string[];
  alt?: string;
  className?: string;
  style?: React.CSSProperties;
  enableZoom?: boolean;
  enablePan?: boolean;
  enableRotate?: boolean;
  enableFullscreen?: boolean;
  minScale?: number;
  maxScale?: number;
  initialScale?: number;
  wheel?: {
    step?: number;
  };
  doubleClick?: {
    disabled?: boolean;
    step?: number;
  };
  onImageLoad?: () => void;
  onImageError?: () => void;
}

const ImageViewer: React.FC<ImageViewerProps> = ({
  urls,
  alt = '图片',
  className = '',
  style = {},
  enableZoom = true,
  enablePan = true,
  enableRotate = true,
  enableFullscreen = true,
  minScale = 0.1,
  maxScale = 3,
  initialScale = 1,
  wheel = { step: 0.1 },
  doubleClick = { disabled: false, step: 0.5 },
  onImageLoad,
  onImageError,
}) => {
  const [rotation, setRotation] = useState(0);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [currentIndex, setCurrentIndex] = useState(0);
  // const [imageLoaded, setImageLoaded] = useState(false);
  const transformRef = useRef<any>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const imageRef = useRef<HTMLImageElement>(null);

  // 获取当前图片URL
  const currentUrl = urls && urls.length > 0 ? urls[currentIndex] : '';
  const hasMultipleImages = urls && urls.length > 1;

  // 处理图片加载
  const handleImageLoad = () => {
    // setImageLoaded(true);
    onImageLoad?.();
  };

  const handleImageError = () => {
    // setImageLoaded(false);
    onImageError?.();
  };

  // 旋转图片
  const handleRotate = (direction: 'left' | 'right') => {
    const newRotation = direction === 'left' ? rotation - 90 : rotation + 90;
    setRotation(newRotation);
  };

  // 重置所有变换状态
  const resetAllTransforms = () => {
    setRotation(0); // 重置旋转角度
    if (transformRef.current) {
      transformRef.current.resetTransform(); // 重置zoom、平移等所有变换
    }
  };

  // 重置变换
  const handleReset = () => {
    resetAllTransforms();
  };

  // 切换到上一张图片
  const handlePrevious = () => {
    if (hasMultipleImages) {
      const newIndex = currentIndex > 0 ? currentIndex - 1 : urls.length - 1;
      setCurrentIndex(newIndex);
      setTimeout(() => {
        resetAllTransforms(); // 重置所有变换状态
      }, 0);
    }
  };

  // 切换到下一张图片
  const handleNext = () => {
    if (hasMultipleImages) {
      const newIndex = currentIndex < urls.length - 1 ? currentIndex + 1 : 0;
      setCurrentIndex(newIndex);
      setTimeout(() => {
        resetAllTransforms(); // 重置所有变换状态
      }, 0);
    }
  };

  // 全屏切换
  const toggleFullscreen = () => {
    if (!document.fullscreenElement) {
      containerRef.current?.requestFullscreen();
      setIsFullscreen(true);
    } else {
      document.exitFullscreen();
      setIsFullscreen(false);
    }
  };

  // 监听全屏状态变化
  useEffect(() => {
    const handleFullscreenChange = () => {
      setIsFullscreen(!!document.fullscreenElement);
    };

    document.addEventListener('fullscreenchange', handleFullscreenChange);
    return () => {
      document.removeEventListener('fullscreenchange', handleFullscreenChange);
    };
  }, []);

  // 工具栏按钮
  const Toolbar = () => (
    <div className="image-viewer-toolbar">
      <Space size="small">
        {/* 图片导航按钮 */}
        {hasMultipleImages && (
          <>
            <Tooltip title="上一张">
              <Button
                type="text"
                icon={<LeftOutlined />}
                onClick={handlePrevious}
              />
            </Tooltip>
            <Tooltip title="下一张">
              <Button
                type="text"
                icon={<RightOutlined />}
                onClick={handleNext}
              />
            </Tooltip>
            <div className="image-counter">
              {currentIndex + 1} / {urls.length}
            </div>
          </>
        )}

        {enableZoom && (
          <>
            <Tooltip title="放大">
              <Button
                type="text"
                icon={<ZoomInOutlined />}
                onClick={() => transformRef.current?.zoomIn()}
              />
            </Tooltip>
            <Tooltip title="缩小">
              <Button
                type="text"
                icon={<ZoomOutOutlined />}
                onClick={() => transformRef.current?.zoomOut()}
              />
            </Tooltip>
          </>
        )}

        {enableRotate && (
          <>
            <Tooltip title="向左旋转">
              <Button
                type="text"
                icon={<RotateLeftOutlined />}
                onClick={() => handleRotate('left')}
              />
            </Tooltip>
            <Tooltip title="向右旋转">
              <Button
                type="text"
                icon={<RotateRightOutlined />}
                onClick={() => handleRotate('right')}
              />
            </Tooltip>
          </>
        )}

        <Tooltip title="重置">
          <Button type="text" icon={<ReloadOutlined />} onClick={handleReset} />
        </Tooltip>

        {enableFullscreen && (
          <Tooltip title={isFullscreen ? '退出全屏' : '全屏'}>
            <Button
              type="text"
              icon={
                isFullscreen ? (
                  <FullscreenExitOutlined />
                ) : (
                  <FullscreenOutlined />
                )
              }
              onClick={toggleFullscreen}
            />
          </Tooltip>
        )}
      </Space>
    </div>
  );

  return (
    <div
      ref={containerRef}
      className={`image-viewer-container ${className}`}
      style={style}
    >
      <div className="image-viewer-content">
        <TransformWrapper
          ref={transformRef}
          initialScale={initialScale}
          minScale={minScale}
          maxScale={maxScale}
          wheel={{ disabled: false, ...wheel }}
          doubleClick={{ disabled: false, ...doubleClick }}
          panning={{ disabled: !enablePan }}
          centerOnInit={true}
          centerZoomedOut={false}
          limitToBounds={false}
          disabled={false}
          pinch={{ disabled: false }}
        >
          <TransformComponent
            wrapperClass="image-viewer-wrapper"
            contentClass="image-viewer-content-wrapper"
          >
            <img
              ref={imageRef}
              src={currentUrl || noPicture}
              alt={alt}
              className="image-viewer-image"
              style={{
                transform: `rotate(${rotation}deg)`,
                transition: 'transform 0.3s ease',
              }}
              onLoad={handleImageLoad}
              onError={handleImageError}
            />
          </TransformComponent>
        </TransformWrapper>

        <Toolbar />
      </div>
    </div>
  );
};

export default ImageViewer;
